//
//  ShoppingReplaceView.swift
//  DollBuy
//
//  Created by 郑东喜 on 2016/12/7.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  购物车替换界面

import UIKit

import WebKit

class ShoppingReplaceView: WKBaseViewController {
    


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        
        //加载URL
        let urlStr = shoppingCarArray.lastObject
        
        let url = URL.init(string: urlStr as! String)
        
        DispatchQueue.main.async {
            
            //根据是否有网络状态加载断网图片
            StatusBarCheck.shared.networkingStatesFromStatebar { (result) in
                
                if result == "notReachable" {
                    DispatchQueue.main.async {
                        DispatchQueue.main.async {
                            
                            self.urlRequestCache = NSURLRequest.init(url: url!, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 0)
                            self.webView.load(self.urlRequestCache as URLRequest)
                            
                        }
                    }
                    
                } else {
                    
                    DispatchQueue.main.async {
                        
                        self.urlRequestCache = NSURLRequest(url: url!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 10)
                        self.webView.load(self.urlRequestCache as URLRequest)
                        
                    }
                }
            }

        }

    }

    
    //拦截操作
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        url = (navigationAction.request.url?.absoluteString)!
        
        //XFLog(message: url)
        
        textView.text = self.url
        
        if navigationAction.navigationType == WKNavigationType.linkActivated || url == "http://\(yuMing)/app/order_pay.aspx" {
            

            if self.url.contains("?") {
                    self.url = self.url + ("&devtype=1&token=") + (token)
                } else {
                    self.url = self.url + ("?devtype=1&token=") + (token)
                }
    
            shoppingCarArray.add(url)
            aaa(str: self.url)
        
            decisionHandler(.cancel)
            
        } else {
            decisionHandler(.allow)
            
        }

    }
    
    //url---
    func aaa(str : String) -> Void {
        
        let vvv = ShoppingViewController()
        vvv.url = str
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vvv, animated: true)
    }

}
